#include "RingQueue.hpp"
#include "Thread.hpp"
#include "Task.hpp"
#include <ctime>

using namespace yss;
using RingQueue_t = RingQueue<Task>;

// 消费
void Consumer(RingQueue_t &rq, const string& name) // 引用是为了使用同一个队列
{
    while (true)
    {
        sleep(2);
        //获取任务
        Task t;
        rq.Pop(&t);
        cout << "Consumer Task is: " << "[" << name << "]" << endl;
        //执行任务
        t.Download();
    }
}
// 生产
void Productor(RingQueue_t &rq, const string& name)
{
    while (true)
    {
        Task t;
        //获取任务放入队列
        rq.Enqueue(t);
        cout << "Productor: " << "[" << name << "]" << endl;
    }
}
// 共用代码
void InitComm(vector<Thread<RingQueue_t>> *thread, int num, RingQueue_t &rq, func_t<RingQueue_t> func)
{
    for (int i = 0; i < num; i++)
    {
        string name = "thread-" + to_string(i + 1);
        thread->emplace_back(func, rq, name); // 保存数据
    }
}
// 消费者
void InitConsumer(vector<Thread<RingQueue_t>> *thread, int num, RingQueue_t &rq)
{
    InitComm(thread, num, rq, Consumer); // 复用
}
// 生产者
void InitProductor(vector<Thread<RingQueue_t>> *thread, int num, RingQueue_t &rq)
{
    InitComm(thread, num, rq, Productor); // 复用
}
//创建线程
void StartAllThread(vector<Thread<RingQueue_t>> &threads)
{
    for(auto& thread:threads)
    {
        thread.Satrt();
    }
}
// 等待
void WaitAllThread(vector<Thread<RingQueue_t>> &threads)
{
    for (auto &thread : threads)
    {
        thread.Join();
    }
}
int main()
{
    RingQueue_t *rq = new RingQueue_t(10); // 环形队列
    vector<Thread<RingQueue_t>> threads;
    InitProductor(&threads, 2, *rq); // 多生产 -- bq是传引用，保证同一个
    InitConsumer(&threads, 3, *rq);  // 多消费
    StartAllThread(threads); // 创建
    WaitAllThread(threads);           // 等待
    return 0;
}